const mongoose = require('mongoose')
const env = require('./env')
const log = require('./log').log
const utils = require('./utils')

mongoose.connect(env.mongoUri, { useNewUrlParser: true })
const connect = mongoose.connection

connect.on('error', err => {
  console.log(err)
  log(err, 'error')
})
connect.once('open', async () => {
  console.log('********* Mongodb is ready **********')
  const Role = mongoose.model('role')
  const Auth = mongoose.model('auth')
  let results = await Promise.all([Role.find({}), Auth.find({})])
  if (results[0].length === 0) {
    env.roles.forEach(async item => {
      let role = await Role.create(item)
      if (role.code === '0') {
        Auth.create({
          role: role._id.toString(),
          username: env.rootUser.username,
          password: utils.md5Handle(utils.md5Handle(env.rootUser.password, ''), env.rootUser.username),
          nickName: '系统管理员'
        })
      }
    })
  }
})

module.exports = connect